package com.windliven.spoc.modules.init.config.shiro;

import com.windliven.spoc.modules.init.entity.SysRole;
import com.windliven.spoc.modules.init.service.UserService;
import com.windliven.spoc.modules.init.utils.JwtHelper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author tomsun28
 * @date 18:07 2018/3/3
 */
public class JwtRealm extends AuthorizingRealm {

    private static final String JWT = "jwt:";
    private static final int NUM_4 = 4;
    private static final char LEFT = '{';
    private static final char RIGHT = '}';

    @Autowired
    private UserService userService;

    @Override
    public Class<?> getAuthenticationTokenClass() {
        // 此realm只支持jwtToken
        return JwtToken.class;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = (String) principalCollection.getPrimaryPrincipal();
        if (token != null) {
            Map<String, String> map = JwtHelper.verifyToken(token);
            String username = map.get("username");
            Set<String> roles = userService.getRoles(username);
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            if(null!=roles&&!roles.isEmpty()) {
                info.addRoles(roles);
            }
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (!(authenticationToken instanceof JwtToken)) {
            return null;
        }
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String jwt = (String) jwtToken.getCredentials();
        Map<String, String> map;
        String username = null;
        try {
            // 预先解析Payload
            // 没有做任何的签名校验
            map = JwtHelper.verifyToken(jwt);
            username = map.get("username");
        } catch (Exception e) {
            //令牌格式错误
            throw new AuthenticationException("errJwt");
        }
        if (null == username) {
            //令牌无效
            throw new AuthenticationException("errJwt");
        }
        return new SimpleAuthenticationInfo(jwtToken, jwtToken, this.getName());
    }
}
